package vn.ugame.processor;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.exception.InvalidArgumentException;
import vn.ugame.model.bl.OrderService;
import vn.ugame.model.entity.Customer;
import vn.ugame.model.entity.Order;
import vn.ugame.utility.Imei;
import vn.ugame.utility.Security;

@ServiceProcessor("activate-online")
public class ActivateOnlineProcessor implements Processor {

    @Override
    public void process(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String imei = request.getParameter("imei");
        String encrypteCode = request.getParameter("code");
        String secretKey = (String) request.getAttribute("secretKey");

        if (!Imei.getInstance().validate(imei)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        OrderService orderService = new OrderService();
        Customer customer = null;
        if (imei != null && encrypteCode == null) {
            try {
                Order order = orderService.findOrderByIMEI(imei);
                if(order!=null){
                    customer = order.getCustomer();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }
        } else if (imei != null && encrypteCode != null) {            
            String code = Security.getInstance().decrypt(encrypteCode, secretKey);
            try {
                orderService.activateApp(code, imei);
            } catch (InvalidArgumentException ex) {
            } catch (Exception ex) {
                ex.printStackTrace();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        String message = null;
        if (customer == null) {
            message = "0;";
        } else {
            message = "1;" + customer.getId() + ";";
        }
        String encrytedMessage = Security.getInstance().encrypt(message, secretKey);
        response.getWriter().write(encrytedMessage);
        response.getWriter().close();
    }
}
